package cn.edu.sgu.www.mhxysy.chain.login.impl;

import cn.edu.sgu.www.mhxysy.chain.login.UserLoginHandler;
import cn.edu.sgu.www.mhxysy.dto.system.UserLoginDTO;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.strategy.cache.CacheStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录处理-验证码校验
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class CaptchaHandler implements UserLoginHandler {

    private Object params;
    private UserLoginHandler next;

    private final CacheStrategy redisCacheStrategy;

    @Autowired
    public CaptchaHandler(CacheStrategy redisCacheStrategy) {
        this.redisCacheStrategy = redisCacheStrategy;
    }

    @Override
    public void handle() {
        UserLoginDTO loginDTO = (UserLoginDTO) params;

        // 获取正确的验证码
        String realCode = redisCacheStrategy.getStorage(loginDTO.getUuid());

        // 得到的验证码为空，则获取验证码到登录之间的时间已经过了3分钟，验证码过期已经被删除
        if (realCode == null) {
            log.debug("登录失败，验证码已过期！");

            throw new GlobalException(ResponseCode.BAD_REQUEST, "验证码已过期，请重新获取");
        }

        // 得到用户输入的验证码
        String code = loginDTO.getCode();

        // 验证码校验
        if (!code.equalsIgnoreCase(realCode)) {
            log.debug("登录失败，验证码错误！");

            throw new GlobalException(ResponseCode.BAD_REQUEST, "验证码错误");
        }

        if (next != null) {
            next.handle();
        }
    }

    @Override
    public void setParams(Object params) {
        this.params = params;
    }

    @Override
    public void setNext(UserLoginHandler next) {
        this.next = next;
    }

}